<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/6
 * Time: 17:16
 */

namespace App\Game;

use App\Game\Traits\SunBetTrait;
use App\Models\Def\MainGamePlat;
use App\Models\OddsHandicap;
use App\Models\QuotaHandicap;
use Carbon\Carbon;

class sunbet extends Game
{
    use SunBetTrait;

    const API_TOKEN = '/api/oauth/token';
    const API_USER_LOGIN = '/api/player/authorize';
    const API_BALANCE = '/api/player/balance';
    const API_CREDIT = '/api/wallet/credit';
    const API_DEBIT = '/api/wallet/debit';
    const API_GAME = '/gamelauncher';
    const API_LOBBY_GAME_PC = '/SBlobby';
    const API_LOBBY_GAME_MOBILE = '/SBmlobby';
    const API_HISTORY = '/api/history/bets';


    const API_KICK = '/api/player/deauthorize';


    private $platName = 'sunbet';
    private $xSgsDate;


    public function __construct()
    {
        $this->xSgsDate = Carbon::now()->timezone('UTC')->format('Y-m-d\TH:m:s\Z');

        $this->header = [
            "Accept" => "application/json",
            "Content-Type" => "application/json",
        ];
        $this->adds = [
            'main_game_plat_code' => $this->platName,
            'plat_type' => 'live',
            'status' => 1
        ];
    }

    public function getLength()
    {
        return $this->length;
    }

    public function getPre()
    {
        return $this->pre;
    }

    /**
     * gameapi
     * 2018/9/19 16:15
     * Administrator
     * __get
     *
     * @param string $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->$key;
    }

    public function __set($key, $value)
    {
        $this->$key = $value;
    }

    /**
     * gameapi
     * 2018/9/24 14:16
     * Administrator
     * curlCreateMember
     * 创建用户
     * @param $accountUserName
     * @param $password
     * @param $request
     * @return array
     */
    public function curlCreateMember($accountUserName, $password)
    {
        $token = $this->token();
        if (!$token){
            return ['success' => false, 'data' => [], 'message' => '创建用户失败'];
        }
        $authtoken = $this->userToken($accountUserName, $token);
        if ($authtoken) {
            return ['success' => true, 'data' => ['accountUserName' => $accountUserName, 'password' => $password], 'message' => ''];
        } else {
            return ['success' => false, 'data' => [], 'message' => '创建用户失败'];
        }
    }

    /**
     * gameapi
     * 2018/9/24 14:15
     * Administrator
     * curlGetBalance
     * 查询余额
     * @param $accountUserName
     * @return array
     */
    public function curlGetBalance($accountUserName)
    {
        $params = [
            'userid' => $accountUserName,
            'cur' => 'RMB'
        ];

        $url = $this->gameUrl . self::API_BALANCE.'?'.http_build_query($params);
        $token = $this->token();
        if (!$token){
            return ['success' => false, 'data' => [], 'message' => '查询余额失败，token错误'];
        }
        $header = array_merge($this->header, ['Authorization' => 'Bearer '.$token]);
        $output = $this->get_data($url, $header);
        $output = json_decode($output, true);
        if (isset($output['err']) && $output['err'] > 0) {
            return ['success' => false, 'data' => [], 'message' => '查询余额失败，错误原因：' . $output['errdesc']];
        }
        if (isset($output['bal'])) {
            return ['success' => true, 'data' => ['balance' => $output['bal']], 'message' => ''];
        }
        return ['success' => false, 'data' => [], 'message' => '请求平台失败，状态未知'];

    }


    //转入游戏
    public function curlTransferIn($accountUserName, $price, $transferid)
    {
        $token = $this->token();
        if (!$token){
            return ['success' => false, 'data' => [], 'message' => '查询余额失败，token错误'];
        }
        $header = array_merge($this->header, ['Authorization' => 'Bearer '.$token]);
        $json = [
            'userid' => $accountUserName,
            'amt' => $price,
            'cur' => 'RMB',
            'txid' => $transferid,
            'timestamp' => Carbon::now()->format('c'),
            'desc' => '转入游戏'

        ];
        $url = $this->gameUrl . self::API_CREDIT;
        $json = json_encode($json);
        $output = $this->post_data($url, $json, $header);
        $output = json_decode($output, true);
        if (isset($output['err']) && $output['err'] > 0) {
            return ['success' => false, 'data' => [], 'message' => '转帐失败，错误原因：' . $output['errdesc']];
        }
        if (isset($output['bal'])) {
            return ['success' => true, 'data' => ['transferid' => $output['txid'], 'transfer_state' => 1], 'message' => ''];
        }
        return ['success' => false, 'data' => [], 'message' => '请求平台失败，状态未知'];
    }


    //转出游戏
    public function curlTransferTo($accountUserName, $price, $transferid)
    {
        $token = $this->token();
        if (!$token){
            return ['success' => false, 'data' => [], 'message' => '查询余额失败，token错误'];
        }
        $header = array_merge($this->header, ['Authorization' => 'Bearer '.$token]);
        $json = [
            'userid' => $accountUserName,
            'amt' => $price,
            'cur' => 'RMB',
            'txid' => $transferid,
            'timestamp' => Carbon::now()->format('c'),
            'desc' => '转出游戏'

        ];
        $url = $this->gameUrl . self::API_DEBIT;
        $json = json_encode($json);
        $output = $this->post_data($url, $json, $header);
//        file_put_contents('/home/gameapi/storage/logs/test.log', 'qqqqqq...user_token_error...'.$output.PHP_EOL, FILE_APPEND);
        $output = json_decode($output, true);
        if (isset($output['err']) && $output['err'] > 0) {
            return ['success' => false, 'data' => [], 'message' => '转出游戏，错误原因：' . $output['errdesc']];
        }
        if (isset($output['bal'])) {
            return ['success' => true, 'data' => ['transferid' => $output['txid'], 'transfer_state' => 1], 'message' => ''];
        }
        return ['success' => false, 'data' => [], 'message' => '请求平台失败，状态未知'];
    }


    //查询订单状态
    public function curlCheckTransfer($request)
    {
        return ['success' => false, 'data' => ['transfer_state' => -1], 'message' => '此平台没有次接口'];
    }


    //踢线
    public function curlKick($request)
    {
       /* $json = [
            'userid' => $request->get('accountUserName'),

        ];

        $url = $this->gameUrl . self::API_KICK;
        $output = $this->sunBetRequest('POST', [], $url, $this->header, $json);
        $output = json_decode($output, true);
        if (array_key_exists('err', $output)) {
            if (is_null($output['err'])) {
                return ['success' => true, 'data' => [], 'message' => '成功'];
            } else {
                return ['success' => false, 'data' => [], 'message' => '删除玩家会话失败，错误原因：' . $output['errdesc']];
            }
        } else {
            return ['success' => false, 'data' => [], 'message' => '请求平台失败，状态未知'];
        }
        */
        return ['success' => false, 'data' => [], 'message' => '请求平台失败，状态未知'];
    }


    /**
     * gameapi
     * 2018/9/24 16:35
     * Administrator
     * curlJoinGame
     * 进入游戏
     * @param $request
     * @return array
     */
    public function curlJoinGame($request)
    {
        $token = $this->token();
        if (!$token){
            return ['success' => false, 'data' => [], 'message' => '启动游戏失败,token失败'];
        }
        $authtoken = $this->userToken($request->accountUserName, $token);
        if (!$authtoken) {
            return ['success' => false, 'data' => [], 'message' => '启动游戏失败，用户认证失败'];
        }
        if ($request->is_lobby) {
            $url = $this->joinGameUrl . self::API_LOBBY_GAME_PC . "?token=" . $authtoken;
        } else {
            $url = $this->joinGameUrl . self::API_GAME . "?gpcode=" . $this->gameProvider . "&gcode=" . $request->gamecode . "&token=" . $authtoken;
        }
        return ['success' => true, 'data' => ['url' => $url], 'message' => '成功'];

    }

    /**
     * gameapi
     * 2018/9/24 16:35
     * Administrator
     * curlJoinMobileGame
     * 手机端进入游戏
     * @param $request
     * @return array
     */
    public function curlJoinMobileGame($request)
    {
        $token = $this->token();
        if (!$token){
            return ['success' => false, 'data' => [], 'message' => '启动游戏失败,token失败'];
        }
        $authtoken = $this->userToken($request->accountUserName, $token, 1);
        if (!$authtoken) {
            return ['success' => false, 'data' => [], 'message' => '启动游戏失败，用户认证失败'];
        }
        if ($request->is_lobby) {
            $url = $this->joinGameUrl . self::API_LOBBY_GAME_MOBILE . "?token=" . $authtoken;
        } else {
            $url = $this->joinGameUrl . self::API_GAME . "?gpcode=" . $this->gameProvider . "&gcode=" . $request->gamecode . "&token=" . $authtoken;
        }
        return ['success' => true, 'data' => ['url' => $url], 'message' => '成功'];
    }


    /**
     * gameapi
     * 2018/12/6 22:15
     * Administrator
     * curlGetBetRecord
     * 游戏抓单
     * @param Carbon $startTime
     * @param Carbon $endTime
     * @return array
     */
    public function curlGetBetRecord(Carbon $startTime, Carbon $endTime)
    {
        $token = $this->token();
        if (!$token){
            return ['success' => false, 'data' => [], 'message' => '游戏抓单失败,token失败'];
        }

        $start_time = $startTime->format('c');
        $end_time = $endTime->format('c');
        $params = [
            'startdate' => urlencode($start_time),
            'enddate' => urlencode($end_time),
            'issettled' => true,
        ];
        $header = [
            'X-Tgp-Accept' => 'json',
            'Authorization' => 'Bearer '.$token
        ];
        $url = $this->gameUrl . self::API_HISTORY.'?startdate='.$params['startdate'].'&enddate='.$params['enddate'].
        '&issettled=true';
        $output = $this->get_data($url, $header);
        $output = json_decode($output, true);
        if (isset($output['err']) && $output['err'] > 0) {
            file_put_contents('/home/gameapi/storage/logs/test.log', 'sunbet..getRecord_error...'.$output['errdesc'].PHP_EOL, FILE_APPEND);
            return [];
        }
//        return [];
        return $output;
    }


}